// pages/home/home.js
var bananer = require('../../template/homeTemp.js');
var network = require('../../utils/network_util.js');
var utils = require('../../utils/utils.js');
var api = require('../../utils/api.js');
var baseInfo = require('../../utils/base_info.js');
const app = getApp();

var Zan = require('../../dist/index');

Page(Object.assign({}, Zan.TopTips, {

  /**
   * 页面的初始数据
   */
  data: {
    bananer: {
      autoplay: true,
      interval: 5000,
      duration: 300,
      indicatorDots: true,
      circular: true,
      height: utils.windowSize().winWidth / 750 * 400
    },
    frame: [],
    popOn: null,
    coupon: [],
    showModalStatus: false,
    screenHeight: 0,
    isyouhuishow: false,
    temp: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (app.globalData.userId) {
      wx.setNavigationBarTitle({
        title: app.globalData.userAndTenantInfo.tenant.name,
      })
      bind(options);
      network._post_json(this, api.getHomeFarem, {}, success);
    } else {
      // 由于 openId 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userAndTenantInfoCallback = res => {
        wx.setNavigationBarTitle({
          title: res.tenant.name,
        })
        bind(options);
        network._post_json(this, api.getHomeFarem, {}, success);
      }
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
   
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
    this.setData({
      frame: []
    })
    /**
    * 获取个人及商家信息
    */
    if (app.globalData.userId) {
      network._post_json(this, api.getHomeFarem, {}, success);
    } else {
      // 由于 openId 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userAndTenantInfoCallback = res => {
        network._post_json(this, api.getHomeFarem, {}, success);
      }
    }
    if (app.globalData.openId == null) {
      baseInfo.getBaseInfo(this);
      if (app.globalData.openId) {
        network._post_json(this, api.getHomeFarem, {}, success);
      } else {
        // 由于 openId 是网络请求，可能会在 Page.onLoad 之后才返回
        // 所以此处加入 callback 以防止这种情况
        app.userAndTenantInfoCallback = res => {
          network._post_json(this, api.getHomeFarem, {}, success);
        }
      }
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  onBananerItemClick: function (e) {
    bananer.onBananerItemClick(this, e);
  },

  onNavigateItemClick: function (e) {
    bananer.onNavigateItemClick(this, e);
  },

  onRecommendItemClick: function (e) {
    bananer.onRecommendItemClick(this, e);
  },

  onSpellProductItemClick: function (e) {
    bananer.onSpellProductItemClick(this, e);
  },

  powerDrawer: function (e) {
    bananer.powerDrawer(this, e);
  },
  onAdvertItemClick: function (e) {
    bananer.onAdvertItemClick(this, e);
  },
  // 领取优惠券
  receiveCoupon: function (e) {
    this.setData({
      showModalStatus: false
    })
    bananer.receiveCoupon(this, e)
  },
  //点击领取优惠券
  clickhongbao: function (e) {

    bananer.clickhongbao(this, e)
  }
}))

// 首页控件请求返回结果
var success = function (that, res) {
  // 首页控件请求
  if (res.data.data) {
    for (var i = 0; i < res.data.data.applet.length; i++) {
      if (res.data.data.applet[i].backgroud) {
        res.data.data.applet[i].backgroud = colorRGB2Hex(res.data.data.applet[i].backgroud);
      } else {
        res.data.data.applet[i].backgroud = '#ffffff';
      }
    }
    that.setData({
      frame: that.data.frame.concat(res.data.data.applet),
      popOn: res.data.data.popOn
    })
    if (res.data.data.popOn) {
      if (res.data.data.popOn.status == 1) {
        if (res.data.data.popOn.type == '广告') {
          that.setData({
            showModalStatus: true
          })
        } else {
          if (res.data.data.popOn.linkId) {
            var couponId = res.data.data.popOn.linkId.split(",")
            network._post_json(that, api.getCoupon, { couponId: couponId }, couponSuccess);
          }
        }
      }
    }
  }
}

var couponSuccess = function (that, res) {
  if (res.data.data) {
    var coupon = res.data.data;
    for (var i = 0; i < coupon.length; i++) {
      coupon[i].startTime = utils.formatDate02(new Date(coupon[i].startTime))
      coupon[i].endTime = utils.formatDate02(new Date(coupon[i].endTime))
    }
    that.setData({
      coupon: coupon,
      showModalStatus: true
    })
  }
}

var bindSuccess = function (that, res) {

}

var bind = function (options) {
  if (options.scene) {
    var scene = decodeURIComponent(options.scene);
    if (scene.substring(0, 1) == 'u') {
      wx.request({
        url: api.bindUserFormQRcode,
        data: {
          openId: app.globalData.openId,
          userId: app.globalData.userId,
          tenantId: app.globalData.tenantId,
          distributorId: scene.substring(2, scene.length),
        },
        method: 'POST',
        success: function (res) {
        }
      });
    } else {
      app.globalData.storeId == scene.substring(2, scene.length);
    }
  }
  if (options.shared) {
    wx.request({
      url: api.bindUserFormQRcode,
      data: {
        openId: app.globalData.openId,
        userId: app.globalData.userId,
        tenantId: app.globalData.tenantId,
        distributorId: options.shared,
      },
      method: 'POST',
      success: function (res) {
      }
    });
  }
}

var colorRGB2Hex = function (color) {
  var rgb = color.split(',');
  var r = parseInt(rgb[0].split('(')[1]);
  var g = parseInt(rgb[1]);
  var b = parseInt(rgb[2].split(')')[0]);

  var hex = "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
  return hex;
}